package com.erp.module.ProductionExecuter

import android.app.Activity
import android.content.Intent
import android.util.Log
import android.view.View
import android.widget.AdapterView
import androidx.appcompat.app.AlertDialog
import com.erp.CaptureActivity
import com.erp.R
import com.erp.bean.ProductionExecuteBean
import com.erp.module.ProductionExecute.ProductionExecuteP
import com.erp.module.ProductionExecute.ProductionExecuteXx.ProductionExecuteActivity
import com.erp.module.ProductionExecute.ProdutionExecuteContract
import com.erp.myAdapter.ArrayAdapter
import com.erp.myAdapter.ProductionExecuteAdapter
import com.erp.myFragment.BaseKFragment
import com.erp.permission.PermissionListener
import com.erp.util.Dialogutil
import com.erp.util.Myutil
import com.erp.util.PermissionUtils
import com.erp.view.PullToRefreshView
import kotlinx.android.synthetic.main.fragment_production_execute.*
import kotlinx.android.synthetic.main.fragment_production_execute.Pull
import kotlinx.android.synthetic.main.fragment_production_execute.iv_scan

class FragmengtProductionExecute : BaseKFragment(),ProdutionExecuteContract.ProductionFragmentView, PullToRefreshView.OnHeaderRefreshListener, PullToRefreshView.OnFooterRefreshListener, AdapterView.OnItemClickListener, View.OnClickListener {

    lateinit var mlist : MutableList<ProductionExecuteBean>
    lateinit var P : ProdutionExecuteContract.ProductionFragmentKP
    var updialog: AlertDialog?=null
    lateinit var adapter : ProductionExecuteAdapter
    lateinit var sousuo : SousuoBean
    lateinit var stocks : MutableList<String>
    lateinit var categorys : MutableList<String>
    lateinit var categoryid : MutableList<String>
    override fun getLayoutId(): Int {
        return R.layout.fragment_production_execute
    }

    override fun initData() {
        sousuo= SousuoBean()
        mlist=ArrayList()
        P = ProductionExecuteP(this, context!!,sousuo, mlist)
        adapter= ProductionExecuteAdapter(mlist, activity!!)
        LvProdutionExecute.adapter = adapter
        LvProdutionExecute.onItemClickListener = this
        Pull.setOnHeaderRefreshListener(this)
        Pull.setOnFooterRefreshListener(this)
        TvStartTime.setOnClickListener(this)
        TvEndTime.setOnClickListener(this)
        BtGuolv.setOnClickListener(this)
        TvChongzhi.setOnClickListener(this)
        iv_scan.setOnClickListener(this)
        stocks = ArrayList<String>()
        stocks.add("")
        stocks.add("已备料")
        stocks.add("未备料")
        stocks.add("请求送料")
        stocks.add("送料中")
        val Approvaladapter = ArrayAdapter(activity!!, R.layout.lv_sp_tvitem, stocks)
        SpStock.adapter = Approvaladapter
        AtCategory.setOnClickListener { AtCategory.showDropDown() }
        categoryid = ArrayList()
        categorys = ArrayList()
        P.getcategorys()
        TvStartTime.text = Myutil.getjulidate(-1);
        TvEndTime.text = Myutil.getjulidate(7);
        sousuo.start_time = TvStartTime.text.toString()
        sousuo.end_time = TvEndTime.text.toString()
        Pull.setheader(true)
        Pull.headerRefreshing()
    }

    fun  qingkong(){
        if(isFirstLoad){
            return
        }
        Pull.headerRefreshing()
    }

    override fun getcategoryOk(categorys: MutableList<String>, categoryid: MutableList<String>) {
        this.categoryid = categoryid
        this.categorys = categorys
        Log.d("getcategoryOk",categorys.toString())
        val av = ArrayAdapter(context, android.R.layout.simple_dropdown_item_1line, categorys)
        AtCategory.setAdapter(av)
    }

    override fun getcategoryNo(throwable: String) {
        Log.d("TAAAG", "throwable=$throwable")
    }

    override fun beiliao() {
        if(mlist.size > 0){
            bean = mlist.get(0)
            val intent = Intent(activity, ProductionExecuteActivity::class.java)
            intent.putExtra("code", 1)
            startActivityForResult(intent, 101)
            activity!!.overridePendingTransition(R.anim.start_activity1, R.anim.no_activity)
        }
    }

    override fun xialaOk() {
        updialog?.dismiss()
        Pull.onHeaderRefreshComplete()
        adapter.notifyDataSetChanged()
    }

    override fun xialaNo() {
        updialog?.dismiss()
        Pull.onHeaderRefreshComplete()
    }

    override fun shanglaOk() {
        updialog?.dismiss()
        Pull.onFooterRefreshComplete()
        adapter.notifyDataSetChanged()
    }

    override fun shanglaNo() {
        updialog?.dismiss()
        Pull.onFooterRefreshComplete()
    }

    override fun gainDataOk() {
        adapter.notifyDataSetChanged()
    }
    override fun onFooterRefresh(view: PullToRefreshView) {
        Log.d("onSuccess","shangla")
        P.setcode(0)
        P.shangla()
    }
    override fun onHeaderRefresh(view: PullToRefreshView) {
        Log.d("onSuccess","xiala")
        P.setcode(0)
        P.xiala()
    }

    override fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
        bean = mlist.get(position)
        val intent = Intent(activity, ProductionExecuteActivity::class.java)
        startActivityForResult(intent, 101)
        activity!!.overridePendingTransition(R.anim.start_activity1, R.anim.no_activity)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(data==null||resultCode!= Activity.RESULT_OK){
            return
        }
        when (requestCode) {
            101 ->  {
                Pull.headerRefreshing()
            }
            1 -> if (resultCode == Activity.RESULT_OK) {
                val bundle = data.extras
                //显示扫描到的内容
                var s: String = bundle?.get("result") as String
                Myutil.MyTost(s)
                sousuo.id = s;
                updialog = Myutil.showupdatedialog(activity, "正在刷新", false)
                P.setcode(1)
                P.xiala()
            }
        }
    }

    companion object {
        var bean = ProductionExecuteBean()
    }

    override fun onClick(v: View?) {
        when(v){
            iv_scan -> PermissionUtils.issaomiao(activity!!, object : PermissionListener {
                override fun onSucceed(requestCode: Int, grantPermissions: List<String>) {
                    val intent = Intent()
                    intent.setClass(activity!!, CaptureActivity::class.java)
                    intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
                    startActivityForResult(intent, 1)
                }

                override fun onFailed(requestCode: Int, deniedPermissions: List<String>) {
                    Myutil.MyTost("没有权限，无法扫描")
                }
            })
            TvStartTime -> {
                Dialogutil.showBottoPopupWindow(TvStartTime, "选择开始时间", TvStartTime.text.toString(), activity)
                Myutil.notjianpan(context, tvi)
            }
            TvEndTime -> {
                Dialogutil.showBottoPopupWindow(TvEndTime, "选择结束时间", TvEndTime.text.toString(), activity)
                Myutil.notjianpan(context, tvi)
            }
            BtGuolv -> {
                sousuo.start_time = TvStartTime.text.toString()
                sousuo.end_time = TvEndTime.text.toString()
                sousuo.workshop = EtChejian.text.toString()
                for (i in categorys.indices) {
                    if (categorys[i] == AtCategory.text.toString().trim { it <= ' ' }) {
                        sousuo.category = categoryid[i]
                    }
                }
                sousuo.stock = SpStock.selectedItem.toString()
                Log.d("TAAG",sousuo.toString())
                updialog = Myutil.showupdatedialog(context, "正在过滤", false)
                P.setcode(0)
                P.xiala()
            }
            TvChongzhi -> {
                AtCategory.setText("")
                SpStock.setSelection(0)
                EtChejian.setText("")
                TvStartTime.text = Myutil.getjulidate(-1);
                TvEndTime.text = Myutil.getjulidate(7);
                sousuo.category = ""
                sousuo.workshop = ""
                sousuo.start_time = TvStartTime.text.toString()
                sousuo.end_time = TvEndTime.text.toString()
                sousuo.stock = ""
                sousuo.id=""
                updialog = Myutil.showupdatedialog(context, "正在过滤", false)
                P.setcode(0)
                P.xiala()
            }
        }
    }

    class SousuoBean{
        var id = ""
        var workshop = ""
        var category = ""
        var stock = ""
        var start_time =""
        var end_time =""
        override fun toString(): String {
            return "SousuoBean(id='$id', workshop='$workshop', category='$category', stock='$stock', start_time='$start_time', end_time='$end_time')"
        }
    }
//    9 线圈  7电路板  45白糖  9蓝塘 18红糖 24黄糖 9金刚石  16钛晶石 30紫糖 18处理器 24元件 16宽带 6晶格硅 36绿塘 6量子 8卡晶体 10水玻璃 6透镜 12奇异 8粒子容器
//    8绿马达 16马达 8齿轮  铜，铁，磁，石墨，有机，钛，硅，纳米管，塑料，玻璃，氢气，水，暗物质
}